import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Modal, Button, Select, Tag, Card } from 'antd';

import SelectDetailModal from '@/pages/features/userPermission/user/add/components/selectDetail';
import TagsBlock from '../user/add/components/tagsBlock';
import SpecialBlockList from '../user/add/components/specialBlockList';
import UserManagement from '@/components/UserManagement';

import {
  getUserRoleList,
  getSpecialLabelList,
  batchAuth,
} from '@/services/userControl';

import styles from './index.less';

const BatchPage = () => {
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);

  const [userTags, setuserTags] = useState([]);
  const [roleMsg, setRoleMsg] = useState({
    allRoleList: [],
    checkRoleList: [],
    checkRoleKeys: [],
  });
  const [specialDataList, setspecialDataList] = useState([]);
  const [addAuthorizationModalMsg, setaddAuthorizationModalMsg] = useState({
    visible: false,
    title: '',
  });
  useEffect(() => {
    getSpecialLabel();
  }, []);

  const getRoleListByWorkOrgIdList = async (
    userId: string | number | undefined | null,
    workCheckKeys: React.Key[],
  ) => {
    let msg = {
      userId,
      workOrgIdList: workCheckKeys,
    };
    const res = await getUserRoleList(msg);
    console.log(res);
    const { allRoleList, authorizedRoleList } = res.data;
    setRoleMsg({
      allRoleList: formatRoleList(allRoleList) as any,
      checkRoleList: formatRoleList(authorizedRoleList) as any,
      checkRoleKeys: formatRoleList(authorizedRoleList).map(
        (item) => item.value,
      ) as any,
    });
    // setfunctionAuthorizationShow(true);
  };
  const formatRoleList = (data: any[]) => {
    const arr = [];
    if (Array.isArray(data) && data.length > 0) {
      for (const item of data) {
        arr.push({
          value: item.id,
          label: `${item.organizationName}（${item.roleName}）`,
        });
      }
    }
    return arr;
  };
  const removeCurrentTagHandle = (val: string) => {
    const newTags = userTags.filter(
      (item: { value: string }) => item.value !== val,
    );
    setuserTags(newTags);
  };

  const removeCurrentRoleTagHandle = useCallback((val) => {
    const newTags = roleMsg.checkRoleList.filter((item) => item.value !== val);
  }, []);
  const formatUesrTagsData = (data: any) => {
    let _data = [];
    if (Array.isArray(data) && data.length > 0) {
      for (const item of data) {
        _data.push({
          value: item.id,
          label: item.name,
        });
      }
    }
    return _data;
  };
  const handleSubmit = useCallback((data: any) => {
    console.log(data, 'handleSubmit');
    setuserTags(formatUesrTagsData(data.tags));
    getRoleListByWorkOrgIdList(null, data.departmentTreeCheckKeys);
    setIsModalVisible(false);
  }, []);
  const handleCancel = useCallback(() => {
    setIsModalVisible(false);
  }, []);

  const getSpecialLabel = async () => {
    const res = await getSpecialLabelList({});
    console.log(res);
    setspecialDataList(res.data);
  };
  const specialRemoveHandle = useCallback(
    (id, data) => {
      const newSpecialData = specialDataList.filter((item) => item.id !== id);
      setspecialDataList(newSpecialData);
    },
    [specialDataList],
  );
  const addEditSpecialDataHandle = useCallback(
    (type, data) => {
      console.log(type, data);
      setspecialDataList(data);
    },
    [specialDataList],
  );
  const filterSpecialData = (data: any[]) => {
    let arr = [];
    for (const item of data) {
      if (item.selected) {
        let valueIds = [],
          values = [];
        for (const item2 of item.labelValues) {
          if (item2.selected) {
            valueIds.push(item2.id);
            values.push(item2.value);
          }
        }
        arr.push({
          sysLabelId: item.id,
          valueIds,
          values,
        });
      }
    }
    return arr;
  };
  const saveData = async () => {
    let msg = {
      userIds: userTags.map((item) => item.value),
      roleIds: roleMsg.checkRoleKeys,
      labels: filterSpecialData(specialDataList),
    };
    console.log(msg);
    const saveRes = await batchAuth(msg);
    console.log(userTags, roleMsg, specialDataList);
    console.log(saveRes);
  };
  const userBtnGroupDom = (
    <>
      <Button
        onClick={() => {
          setIsModalVisible(true);
        }}
      >
        添加
      </Button>
    </>
  );

  const functionBtnGroupDom = (
    <>
      <Button
        onClick={() => {
          setaddAuthorizationModalMsg({
            ...addAuthorizationModalMsg,
            title: '功能授权',
            visible: true,
          });
        }}
      >
        添加
      </Button>
    </>
  );

  return (
    <>
      {addAuthorizationModalMsg.visible && (
        <SelectDetailModal
          visible={addAuthorizationModalMsg.visible}
          title={addAuthorizationModalMsg.title}
          dataSource={roleMsg.allRoleList}
          checkKeys={roleMsg.checkRoleKeys}
          handleOkCallback={(keys, tagsData) => {
            console.log(tagsData);
            setRoleMsg({
              ...roleMsg,
              checkRoleList: tagsData,
              checkRoleKeys: tagsData.map((item: any) => item.value),
            });
            setaddAuthorizationModalMsg({
              ...addAuthorizationModalMsg,
              visible: false,
            });
          }}
          handleCancelCallback={() => {
            setaddAuthorizationModalMsg({
              ...addAuthorizationModalMsg,
              visible: false,
            });
          }}
        ></SelectDetailModal>
      )}
      <UserManagement
        isModalVisible={isModalVisible}
        handleSubmit={handleSubmit}
        handleCancel={handleCancel}
        userList={userTags}
        type={2}
      ></UserManagement>
      <Card title="基本信息">
        <div>
          <div className={styles.title}>选择用户</div>
          <TagsBlock
            dataSource={userTags}
            btnGroupDom={userBtnGroupDom}
            removeCurrentTag={removeCurrentTagHandle}
          ></TagsBlock>
        </div>
        <div>
          <div className={styles.title}>功能授权</div>
          {/* {roleMsg?.checkRoleKeys && roleMsg?.checkRoleKeys.length > 0 && ( */}
          {/* <> */}
          <TagsBlock
            dataSource={roleMsg.checkRoleList}
            btnGroupDom={functionBtnGroupDom}
            removeCurrentTag={removeCurrentRoleTagHandle}
          ></TagsBlock>
          {/* </> */}
          {/* )} */}
        </div>
        <div>
          <div className={styles.title}>特殊数据授权</div>
          <SpecialBlockList
            dataSource={specialDataList}
            pageType={'add'}
            removeHandleCallback={specialRemoveHandle}
            addEditSpecialDataHandle={addEditSpecialDataHandle}
            formDisabled={false}
          ></SpecialBlockList>
        </div>
        <Button type="primary" onClick={saveData} style={{ marginTop: '20px' }}>
          保存并提交
        </Button>
      </Card>
    </>
  );
};

export default BatchPage;
